import { combineResolvers } from 'graphql-resolvers'
import auth from '../../middlewares/auth'

module.exports = {
  ShowType: {
    invisible: -1,
    normal: 0,
    pin: 1
  },
  Query: {
    tags: async (
      root,
      { name, folderId, show },
      { services: { $tag }, user }
    ) => {
      const result = await $tag.findAllTags({ name, folderId, show })
      return result
    }
  },
  Mutation: {
    createTag: combineResolvers(
      auth,
      async (root, { input }, { services: { $tag }, user }) => {
        let userId = user.id
        console.info('create tag:', input)
        return await $tag.create(userId, input)
      }
    ),
    pinTag: combineResolvers(
      auth,
      async (root, { id, show }, { services: { $tag }, user }) => {
        // TODO: Add authorization
        // if (!user.roles) {
        //   throw new Error(`${ERRORS.DBERR.ERR_UNAUTHORIZED_OPERATION}`)
        // }
        console.info('pin tag:', id, show)
        return await $tag.pin(id, show)
      }
    ),
    removeTag: combineResolvers(
      auth,
      async (root, { id }, { services: { $tag }, user }) => {
        let userId = user.id
        console.info('remove tag:', id)
        return await $tag.remove(id, userId)
      }
    )
  },
  Tag: {
    tags: ({ id }, arg, { dataloaders: { tagLoaderByFolder } }) => {
      return tagLoaderByFolder.load(id)
    }
  }
}
